﻿using System.Windows;
using System.Windows.Controls;

namespace DeepEarth.Toolkit.Common.Utilities
{
    public class TextBoxBindingTrigger
    {
        #region Properties
        public static readonly DependencyProperty UpdateSourceOnChangeProperty = DependencyProperty.RegisterAttached("OnChange", typeof(bool), typeof(TextBoxBindingTrigger), new PropertyMetadata(false, OnOnChangeChanged));

        public static bool GetOnChange(DependencyObject obj)
        {
            return (bool)obj.GetValue(UpdateSourceOnChangeProperty);
        }

        public static void SetOnChange(DependencyObject obj, bool value)
        {
            obj.SetValue(UpdateSourceOnChangeProperty, value);
        }
        #endregion

        static void OnOnChangeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var target = obj as TextBox;
            if (target != null)
            {
                if ((bool)e.NewValue)
                    target.TextChanged += OnTextChanged;
                else
                    target.TextChanged -= OnTextChanged;
            }
        }

        static void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            var target = sender as TextBox;
            if (target != null)
            {
                var binding = target.GetBindingExpression(TextBox.TextProperty);
                if (binding != null)
                    binding.UpdateSource();
            }
        }
    }
}